package com.example.userservice.controller;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.common.AjaxResult;
import com.example.common.AppVariable;
import com.example.common.PasswordUtils;
import com.example.userservice.model.Userinfo;
import com.example.userservice.service.impl.UserinfoServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.flyway.FlywayDataSource;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 晨哥
 * @since 2024-04-12
 */
@RestController
@RequestMapping("/user")
public class UserinfoController {
    @Autowired
    private UserinfoServiceImpl userinfoService;

    @RequestMapping("/add")
    public AjaxResult AddUser(Userinfo userinfo) {
        // 1、检查参数是否正确
        if (userinfo == null || !StringUtils.hasLength(userinfo.getUsername()) ||
                !StringUtils.hasLength(userinfo.getPassword())) {
            return AjaxResult.fail(-1, "非法参数！");
        }
        // 2、进行插入数据
        userinfo.setPassword(PasswordUtils.encrypt(userinfo.getPassword()));  // 密码加密
        boolean result = userinfoService.save(userinfo);
        if (result) {
            return AjaxResult.success("注册成功！", "");
        } else {
            return AjaxResult.fail(0, "未知错误！");
        }
    }

    @RequestMapping("/login")
    public AjaxResult UserLogin(String username, String password) {
        // 1、检查参数
        if (username == null && password == null && !StringUtils.hasLength(username)
                && !StringUtils.hasLength(password)) {
            return AjaxResult.fail(-1, "非法参数！");
        }
        QueryWrapper<Userinfo> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);  // 使用条件构造器  where username=#{username}
        Userinfo userinfo = userinfoService.getOne(wrapper);
        if (userinfo == null || userinfo.getUid() <= 0) {
            // 此时没有查到
            return AjaxResult.fail(0, "用户名/密码错误！");
        }
        // 进行判断密码是否一致
        if (PasswordUtils.dencreypt(password, userinfo.getPassword())) {
            return AjaxResult.fail(0, "用户名/密码错误！");
        }
        // 登录成功，生成 token
        Map<String, Object> playload = new HashMap<>() {
            private static final long serialVersionUID = 1L;

            {
                put("uid", userinfo.getUid());
                put("manager", userinfo.getManager()); // 添加是否为管理员
                put("exp", System.currentTimeMillis() + 1000 * 60 * 60 * 24); // 设置过期时间
            }
        };
        String token = JWTUtil.createToken(playload, AppVariable.JWT_KEY.getBytes());   //生成token
//        System.out.println(token);
        return AjaxResult.success(token);
    }
}
